import requests,pymysql

'''''MySQL配置'''
host = '127.0.0.1'
users = 'root'
pwd = '123123'
port = 3306
dbs = 'ans'

def mysql(heroId,name,alias,attack,defense,magic,difficulty,selectAudio,banAudio,goldPrice,couponPrice,keywords):
    value = ((heroId,name,alias,attack,defense,magic,difficulty,selectAudio,banAudio,goldPrice,couponPrice,keywords))
    db = pymysql.connect(host=host, user=users,passwd=pwd,port=port, db=dbs)
    cursor = db.cursor()
    sql = "INSERT INTO heros(heroId,name,alias,attack,defense,magic,difficulty,selectAudio,banAudio,goldPrice,couponPrice,keywords) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    try:
        cursor.execute(sql, value)
        db.commit()
        print('success!')
    except Exception as e:
        db.rollback()
        print("error.", e)
    db.close()





def func_Hero(res):
    hero_list = res['hero']
    for heros in hero_list:
        heroId = heros['heroId']
        name = heros['name']
        alias = heros['alias']
        attack = heros['attack']
        defense = heros['defense']
        magic = heros['magic']
        difficulty = heros['difficulty']
        selectAudio = heros['selectAudio']
        banAudio = heros['banAudio']
        goldPrice = heros['goldPrice']
        couponPrice = heros['couponPrice']
        keywords = heros['keywords']
        print(heroId,name,alias,attack,defense,magic,difficulty,selectAudio,banAudio,goldPrice,couponPrice,keywords)
        mysql(heroId,name,alias,attack,defense,magic,difficulty,selectAudio,banAudio,goldPrice,couponPrice,keywords)

'''同步下载'''
def down(url):
    res = requests.get(url)
    return res

if __name__ == '__main__':
    url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2767888'
    '''第一步，获取英雄列表'''
    res = down(url).json()
    func_Hero(res)
